package com.abc.recycling.controller;

import com.abc.recycling.model.User;
import com.abc.recycling.service.AddressService;
import com.abc.recycling.service.OrderService;
import com.abc.recycling.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/profile")
public class ProfileController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private AddressService addressService;

    @GetMapping
    public String profile(Model model) {
        // 获取当前登录用户
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated() || "anonymousUser".equals(auth.getPrincipal())) {
            return "redirect:/login";
        }

        try {
            // 从数据库获取完整的用户信息
            String username = auth.getName();
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return "redirect:/login";
            }

            // 添加用户信息
            model.addAttribute("user", user);

            // 添加统计数据
            model.addAttribute("totalOrders", orderService.countOrdersByUser(user.getId()));
            model.addAttribute("totalWeight", orderService.getTotalWeightByUser(user.getId()));
            model.addAttribute("averageRating", orderService.getAverageRatingByUser(user.getId()));
            model.addAttribute("totalIncome", orderService.getTotalIncomeByUser(user.getId()));

            // 添加地址列表
            model.addAttribute("addresses", addressService.getAddressList(user.getId()));

            return "profile/index";
        } catch (Exception e) {
            // 记录错误日志
            e.printStackTrace();
            // 添加错误信息到模型
            model.addAttribute("error", "获取个人信息时发生错误");
            return "error";
        }
    }
} 